package com.house.keeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.house.keeper.base.Result;
import com.house.keeper.base.ResultCode;
import com.house.keeper.entity.CityArea;
import com.house.keeper.entity.vo.CityAreaVo;
import com.house.keeper.mapper.CityAreaMapper;
import com.house.keeper.service.CityAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zjj
 * @date 2022-05-23 14:10:08
 *
 * @description 
 */
@Service
public class CityAreaServiceImpl implements CityAreaService {
    @Autowired
    private CityAreaMapper cityAreaMapper;

    /**
     * 分页查询
     *
     * @param cityAreaVo 查询条件
     * @return
     */
    @Override
    public Result selectByPage(CityAreaVo cityAreaVo) {
        PageHelper.startPage(cityAreaVo.getPage(),cityAreaVo.getLimit());

        QueryWrapper<CityArea> wrapper = new QueryWrapper<>();


        List<CityArea> cityAreaList = cityAreaMapper.selectList(wrapper);

        PageInfo<CityArea> pageInfo = new PageInfo<>(cityAreaList);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return
     */
    @Override
    public Result delete(Integer id) {
        int row = cityAreaMapper.deleteById(id);
        if(row<=0){
            return Result.failure(ResultCode.PARAM_IS_INVALID);
        }
        return Result.success();
    }

    /**
     * 添加或修改
     *
     *  回滚：一般抛出的是RuntimeExcept异常
     *  在spring框架下，所有的异常都被org.springframework重写为RuntimeExcept
     * @param cityArea
     * @return
     */
    @Override
    @Transactional
    public Result update(CityArea cityArea) {
        if(cityArea.getId()!=null){

            int row=cityAreaMapper.updateById(cityArea);
            if(row<=0){
                return Result.failure(ResultCode.PARAM_IS_INVALID);
            }
        }else{
//            添加
            int row =cityAreaMapper.insert(cityArea);
            if(row<=0){
                return Result.failure(ResultCode.PARAM_IS_INVALID);
            }
        }
        return Result.success();
    }

    /**
     * 查询所有省份或者市
     *
     * @param pCode 父城市编码
     * @return
     */
    @Override
    public List<CityArea> selectAllCityArea(String pCode) {
        QueryWrapper<CityArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_area_code",pCode);
        return cityAreaMapper.selectList(queryWrapper);
    }


}

